package com.lixueju.security.box.web.authentication;

import com.lixueju.security.box.core.properties.SecurityBoxProperties;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.Base64Utils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lixueju
 * @since 2019/11/12 17:30
 **/
@Data
public class SecurityBoxAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    protected boolean postOnly = true;

    @Autowired
    private SecurityBoxProperties securityBoxProperties;

    public SecurityBoxAuthenticationFilter(String url) {
        super(new AntPathRequestMatcher(url, "POST"));
    }

    protected void setDetails(HttpServletRequest request, SecurityBoxAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        // 删除了自己和自己玩的basic认证
//        HttpServletRequest request = (HttpServletRequest) req;
//        SecurityBoxHttpServletRequestWrapper requestWrapper = new SecurityBoxHttpServletRequestWrapper(request);
//        OAuth2ClientProperties client = securityBoxProperties.getOauth2().getClient();
//        String httpBasic = getHttpBasic(client.getClientId(), client.getClientSecret());
//        requestWrapper.addHeader("Authorization", httpBasic);
//        super.doFilter(requestWrapper, res, chain);
        super.doFilter(req, res, chain);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException, IOException {
        // 内容在其子类执行
        return null;
    }

    //获取httpbasic的串
    private String getHttpBasic(String clientId, String clientSecret) {
        String string = clientId + ":" + clientSecret;
        //将串进行base64编码
        byte[] encode = Base64Utils.encode(string.getBytes());
        return "Basic " + new String(encode);
    }

}
